{% extends "base.html" %}

{% block title %}{{ comic.title }} - 漫画详情{% endblock %}

{% block content %}
<div class="comic-detail-container">
    <!-- 漫画信息头部 -->
    <section class="comic-header">
        <div class="header-content">
            <div class="comic-cover-large">
                {% if comic.cover_image %}
                    <img src="/api/thumbnail/{{ comic.cover_image | urlencode }}?width=400&height=600" 
                         alt="{{ comic.title }}" 
                         class="cover-image"
                         onerror="this.src='/static/images/icons/default-cover.png'">
                {% else %}
                    <div class="cover-placeholder">
                        <span class="placeholder-icon">📖</span>
                        <span class="placeholder-text">暂无封面</span>
                    </div>
                {% endif %}
            </div>
            
            <div class="comic-info">
                <h1 class="comic-title">{{ comic.title }}</h1>
                
                <div class="comic-stats-grid">
                    <div class="stat-item">
                        <span class="stat-label">章节数</span>
                        <span class="stat-value">{{ comic.total_chapters }}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">总页数</span>
                        <span class="stat-value">{{ comic.total_pages }}</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">更新时间</span>
                        <span class="stat-value">{{ comic.updated_at or '未知' }}</span>
                    </div>
                </div>
                
                <div class="action-buttons">
                    {% if comic.chapters %}
                    <button class="action-btn primary" onclick="startReading()">
                        <span class="btn-icon">▶️</span>
                        <span class="btn-text">开始阅读</span>
                    </button>
                    <button class="action-btn secondary" onclick="continueReading()">
                        <span class="btn-icon">📖</span>
                        <span class="btn-text">继续阅读</span>
                    </button>
                    {% else %}
                    <div class="no-chapters">
                        <span class="no-chapters-text">暂无可阅读的章节</span>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </section>

    <!-- 章节列表 -->
    <section class="chapters-section">
        <div class="section-header">
            <h2 class="section-title">章节列表</h2>
            <div class="sort-options">
                <button class="sort-btn active" data-sort="asc">正序</button>
                <button class="sort-btn" data-sort="desc">倒序</button>
            </div>
        </div>
        
        {% if comic.chapters %}
        <div class="chapters-list" id="chapters-list">
            {% for chapter in comic.chapters %}
            <div class="chapter-item" data-chapter-id="{{ chapter.id }}">
                <a href="{{ url_for('main.reader', comic_id=comic.id, chapter_id=chapter.id, page_num=1) }}" 
                   class="chapter-link">
                    <div class="chapter-info">
                        <h3 class="chapter-title">{{ chapter.title }}</h3>
                        <div class="chapter-meta">
                            <span class="page-count">{{ chapter.page_count }}页</span>
                            {% if chapter.updated_at %}
                            <span class="update-time">{{ chapter.updated_at }}</span>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="chapter-actions">
                        <button class="quick-read-btn" onclick="event.preventDefault(); quickRead('{{ chapter.id }}')">
                            <span class="btn-icon">👁️</span>
                        </button>
                        <span class="chapter-arrow">→</span>
                    </div>
                </a>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="empty-chapters">
            <div class="empty-icon">📑</div>
            <div class="empty-title">暂无章节</div>
            <div class="empty-desc">该漫画还没有可阅读的章节</div>
        </div>
        {% endif %}
    </section>

    <!-- 相关操作 -->
    <section class="actions-section">
        <div class="section-header">
            <h2 class="section-title">相关操作</h2>
        </div>
        
        <div class="actions-grid">
            <button class="action-card" onclick="refreshComic()">
                <div class="card-icon">🔄</div>
                <div class="card-title">刷新漫画</div>
                <div class="card-desc">重新扫描该漫画的文件</div>
            </button>
            
            <button class="action-card" onclick="downloadAll()">
                <div class="card-icon">💾</div>
                <div class="card-title">缓存全部</div>
                <div class="card-desc">预缓存所有页面</div>
            </button>
            
            <button class="action-card" onclick="shareComic()">
                <div class="card-icon">📤</div>
                <div class="card-title">分享漫画</div>
                <div class="card-desc">复制漫画链接</div>
            </button>
        </div>
    </section>
</div>
{% endblock %}

{% block scripts %}
<script>
const comicData = {
    id: '{{ comic.id }}',
    title: '{{ comic.title }}',
    chapters: {{ comic.chapters | tojson | safe }},
    totalChapters: {{ comic.total_chapters }},
    totalPages: {{ comic.total_pages }}
};

document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initComicDetail();
    setupEventListeners();
    loadReadingProgress();
});

// 初始化漫画详情页
function initComicDetail() {
    // 格式化更新时间
    const updateTimes = document.querySelectorAll('.update-time');
    updateTimes.forEach(formatTimeElement);
    
    // 设置章节排序
    setupChapterSorting();
}

// 设置事件监听器
function setupEventListeners() {
    // 章节排序按钮
    const sortBtns = document.querySelectorAll('.sort-btn');
    sortBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const sortOrder = this.dataset.sort;
            sortChapters(sortOrder);
            
            // 更新按钮状态
            sortBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
        });
    });
}

// 开始阅读
function startReading() {
    if (comicData.chapters.length > 0) {
        const firstChapter = comicData.chapters[0];
        const readerUrl = `/reader/${comicData.id}/${firstChapter.id}/1`;
        
        showLoading('正在加载阅读器...');
        window.location.href = readerUrl;
    }
}

// 继续阅读
function continueReading() {
    // 从本地存储获取阅读进度
    const progressKey = `reading_progress_${comicData.id}`;
    const progress = localStorage.getItem(progressKey);
    
    if (progress) {
        try {
            const data = JSON.parse(progress);
            const readerUrl = `/reader/${comicData.id}/${data.chapterId}/${data.pageNum}`;
            
            showLoading('正在加载阅读器...');
            window.location.href = readerUrl;
            return;
        } catch (e) {
            console.error('解析阅读进度失败:', e);
        }
    }
    
    // 如果没有进度记录，从第一章开始
    startReading();
}

// 快速阅读
function quickRead(chapterId) {
    const readerUrl = `/reader/${comicData.id}/${chapterId}/1`;
    
    showLoading('正在加载阅读器...');
    window.location.href = readerUrl;
}

// 排序章节
function sortChapters(order) {
    const chaptersList = document.getElementById('chapters-list');
    const chapters = Array.from(chaptersList.children);
    
    chapters.sort((a, b) => {
        const aIndex = comicData.chapters.findIndex(ch => ch.id === a.dataset.chapterId);
        const bIndex = comicData.chapters.findIndex(ch => ch.id === b.dataset.chapterId);
        
        return order === 'desc' ? bIndex - aIndex : aIndex - bIndex;
    });
    
    // 重新排列DOM元素
    chapters.forEach(chapter => chaptersList.appendChild(chapter));
}

// 设置章节排序
function setupChapterSorting() {
    // 默认使用正序排序
    sortChapters('asc');
}

// 刷新漫画
function refreshComic() {
    if (confirm('确定要重新扫描该漫画吗？这可能需要一些时间。')) {
        showLoading('正在刷新漫画...');
        
        fetch(`/api/scan?force=true`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert('漫画刷新成功！');
                location.reload();
            } else {
                throw new Error(data.message);
            }
        })
        .catch(error => {
            console.error('刷新漫画失败:', error);
            alert('刷新失败，请稍后重试');
        })
        .finally(() => {
            hideLoading();
        });
    }
}

// 缓存全部页面
function downloadAll() {
    if (confirm(`确定要缓存所有 ${comicData.totalPages} 页内容吗？这可能需要较长时间和网络流量。`)) {
        showLoading('正在缓存页面...');
        
        let cachedCount = 0;
        const totalChapters = comicData.chapters.length;
        
        // 逐个章节进行缓存
        const cacheChapter = (index) => {
            if (index >= totalChapters) {
                hideLoading();
                alert(`缓存完成！共缓存了 ${cachedCount} 页内容。`);
                return;
            }
            
            const chapter = comicData.chapters[index];
            
            fetch('/api/cache/preload', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    chapter_id: chapter.id,
                    start_page: 1,
                    page_count: chapter.page_count
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    cachedCount += data.data.preloaded_count;
                    // 更新进度
                    const progress = ((index + 1) / totalChapters * 100).toFixed(1);
                    document.querySelector('.loading-text').textContent = 
                        `正在缓存第 ${index + 1}/${totalChapters} 章 (${progress}%)`;
                    
                    // 继续下一章
                    setTimeout(() => cacheChapter(index + 1), 100);
                } else {
                    throw new Error(data.message);
                }
            })
            .catch(error => {
                console.error(`缓存第${index + 1}章失败:`, error);
                // 继续下一章
                setTimeout(() => cacheChapter(index + 1), 100);
            });
        };
        
        cacheChapter(0);
    }
}

// 分享漫画
function shareComic() {
    const url = window.location.href;
    
    if (navigator.share) {
        navigator.share({
            title: comicData.title,
            text: `推荐一部漫画：${comicData.title}`,
            url: url
        });
    } else if (navigator.clipboard) {
        navigator.clipboard.writeText(url).then(() => {
            alert('链接已复制到剪贴板！');
        });
    } else {
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = url;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        alert('链接已复制到剪贴板！');
    }
}

// 加载阅读进度
function loadReadingProgress() {
    const progressKey = `reading_progress_${comicData.id}`;
    const progress = localStorage.getItem(progressKey);
    
    if (progress) {
        try {
            const data = JSON.parse(progress);
            const continueBtn = document.querySelector('.action-btn.secondary .btn-text');
            if (continueBtn && data.chapterTitle) {
                continueBtn.textContent = `继续阅读 ${data.chapterTitle}`;
            }
        } catch (e) {
            console.error('解析阅读进度失败:', e);
        }
    }
}

// 格式化时间元素
function formatTimeElement(element) {
    const timeStr = element.textContent.trim();
    if (timeStr && timeStr !== '未知') {
        try {
            const date = new Date(timeStr);
            const now = new Date();
            const diff = now - date;
            
            if (diff < 24 * 60 * 60 * 1000) { // 一天内
                element.textContent = '今天';
            } else if (diff < 7 * 24 * 60 * 60 * 1000) { // 一周内
                const days = Math.floor(diff / (24 * 60 * 60 * 1000));
                element.textContent = days + '天前';
            } else {
                element.textContent = date.toLocaleDateString('zh-CN');
            }
        } catch (e) {
            element.textContent = '未知';
        }
    }
}
</script>
{% endblock %}